package com.bw.network.interceptor

import com.bw.network.utils.SignUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

class SignInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val  request = chain.request()
        val builder = request.newBuilder()
        val body = request.body()
        val buffer = Buffer()
        body!!.writeTo(buffer)
        val jsonStr = buffer.readUtf8()
        var jsonObject: JSONObject? = null
        try {
            jsonObject = JSONObject(jsonStr)
            val keys = jsonObject.keys()
            val sb = StringBuffer()
            while (keys.hasNext()) {
                val key = keys.next()
                sb.append(jsonObject.getString(key))
            }

            val sign = SignUtils.createSign(sb.toString())
            jsonObject.put("sign", sign)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val signbody = RequestBody.create(
            MediaType.parse("application/json;charset=UTF-8"),
            jsonObject.toString()
        )
        builder.post(signbody)
        return chain.proceed(builder.build())
    }
}